#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "interface.h"
#include "debug.h"
#include <pthread.h>

#define buflen 1024*10

char buf[buflen];


int all_len[1000];

void* test_send_fun(void* arg){
	int i;
	int len;

	for(i=0; i<1000; i++){
		debug_info("send data!\n");
		len = rand() % (buflen);
		all_len[i] = len;
		send_data_sync(0,buf, len);
	}

	return NULL;
}

void* test_recv_fun(void* arg){
	msg_t* msg;
	int i=0;
	while(1){
		msg = recv_data(1);
	 //	if(msg->hr.len != all_len[i++]){
				printf("recv msg  msg->hr.len[%d], all_len[%d], i[%d]\n",
					msg->hr.len, all_len[i], i++);
	//			exit(0);
					 
	//	}
		free_msg(msg);
	}

	return NULL;
}

void usage(char* argv){
	printf("Usage:%s -i id  \n", argv);
}

void send_cb(msg_t* msg){
	free(msg->buf);
}

 
int main(int argc, char* argv[]){
	
	int d = 10;
	queue_t q;
	pthread_t pid_send;
	pthread_t pid_recv;
	int rc;
	int ch;
	int server_id;

   opterr = 0;
   while((ch = getopt(argc, argv, "i:d")) != -1)
   switch(ch)
   {
      case 'i':
		 server_id = atoi(optarg);
		 printf("server id:%d\n", server_id);
		 break;
      case 'd':
         printf("run in daemon\n");
		 break;
      default:
         usage(argv[0]);
		 exit(0);
   }


   sys_init(server_id, send_cb);
    sleep(4);  
   rc = pthread_create(&pid_send, NULL, test_send_fun, NULL);
   assert(rc!=-1);
   rc = pthread_create(&pid_recv, NULL, test_recv_fun, NULL);
   assert(rc!=-1);

   pthread_join(pid_send, NULL);
   pthread_join(pid_recv, NULL);
   sys_exit();


}
